package com.skong.report.extend;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.pac4j.core.profile.CommonProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 该token校验完会返回以下属性
 *  - tenant_id ： 租户编码
 *  - org_code : 组织编码
 *  - current_user_id : 当前用户id
 */
public class TokenUtil {

    private static final Logger logger= LoggerFactory.getLogger(TokenUtil.class);
    private static final String GET_USER_DTO_BY_USER_ID="http://MEMBER-DATA-CENTER/logic/member/member/getUserDtoByUserId";

    public static ArrayList<String> getParameterNames(){
        ArrayList<String> list = new ArrayList<>();
        list.add("tenant_id");
        list.add("org_code");
        list.add("current_user_id");
        list.add("current_user_name");
        return list;
    }

    public static Map<String,String> getParameterValues(RestTemplate restTemplate,String token){
        Map<String,String> map= new HashMap<String,String>();


        if(token!=null&&token.length()>0) {
            logger.info("校验token:{}",token);
            CommonProfile casProfile = TokenConfig.validateToken(token);
            logger.info("校验结果:{}",JSON.toJSONString(casProfile));
            String forObject = restTemplate.getForObject(GET_USER_DTO_BY_USER_ID+"/" + casProfile.getId(), String.class);
            logger.info("请求结果:{}",forObject);
            JSONObject result = JSON.parseObject(forObject);
            logger.info("用户信息:{}",forObject);
            if(result.getString("code").equals("200")){
                JSONObject object=result.getJSONObject("data");
                map.put("tenant_id",object.getString("tenantId"));
                map.put("org_code",object.getString("orgCode"));
                map.put("current_user_id",object.getString("id"));
                map.put("current_user_name",object.getString("userDisplayName"));
                logger.info("读取成功:{}",object);
                return map;
            }else{
                map.put("tenant_id","-");
                map.put("org_code","-");
                map.put("current_user_id","-");
                map.put("current_user_name","-");
                logger.info("读取失败:{}",forObject);
            }
        }else{
            map.put("tenant_id","%");
            map.put("org_code","%");
            map.put("current_user_id","%");
            map.put("current_user_name","%");
            logger.info("未传token:");
        }
        return map;
    }
}
